package org.jeecg.modules.cascv.image.service.merge.liutigui;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.RandomUtil;
import com.NativeImageIO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.util.BayerUtil;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author贺弘烨
 * @Version 2022/3/21
 * description;
 */
@Slf4j
@Service
public class LiutiguiApp3or19Service extends ImageService { //TGMTYY1301_06BH_31_FPRAPP1
    @Value("${imageurl}")
    private String imageurl;

    @Autowired
    private TaskExecutePool taskExecutePool;

    @Override
    public String idsNames() {
        return "6D22H_2FH,6D27H_2FH,6D22H_2FH_UDP,6D27H_2FH_UDP";
    }

    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {


        JSONObject conJson = jsonObject.getJSONObject("Content");

        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }

        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subSecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);
        String nextImageNum = conJson.getString(LaptopConstant.IMAGENUM_FIELD_MAP.get(idsName));
        String dataFrames = conJson.getString(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
        nextImageNum = nextImageNum.split(";")[0];
        dataFrames = dataFrames.split(";")[1].substring(2).trim();
      //  dataFrames = dataFrames.substring(7, dataFrames.length() - 10);
        StringBuilder queue = LaptopConstant.imageData.get(key);

        composite(idsName, key, conJson, dataFrames, queue, nextImageNum, secondStr, subSecondStr);

        return null;
    }

    //TGMTYY1301_06BH_31_FPRAPP1
    public boolean composite(String idsName, String key, JSONObject content, String dataFrames, StringBuilder queue, String currImageNum, String secondStr, String subSecondStr) {

        String lastImageNum = LaptopConstant.imageNumMap.get(key);
        //获取宽度
        int width = Integer.parseInt((content.getString(LaptopConstant.WIDTH_FIELD_MAP.get(idsName))).split(";")[0]);
        //获取高度
        int height = Integer.parseInt((content.getString(LaptopConstant.HEIGHT_FIELD_MAP.get(idsName))).split(";")[0]);

//
//        System.out.println("imageNum=" + lastImageNum);
//        System.out.println("nextImageNum=" + currImageNum);

        if (lastImageNum == null || lastImageNum.equals(currImageNum)) {
            if (queue != null) {
                queue.append(dataFrames);
                LaptopConstant.imageData.put(key, queue);
            } else {
                queue = new StringBuilder();
                queue.append(dataFrames);
                LaptopConstant.imageData.put(key, queue);
            }
        } else {


            String imgHexStr = LaptopConstant.imageData.get(key).toString();
            if (imgHexStr.length()/2 >= width * height) {

                CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {

                    long start = System.currentTimeMillis();
                    byte[] bytes = HexUtil.decodeHex(imgHexStr);
//                    int imageSize = width*height*3;
//                    ByteBuffer byteBuf = ByteBuffer.allocate(imageSize);
//                    byteBuf.put(bytes);
//                    byteBuf.flip();
//                    int length = bytes.length;
//                    byte[] arr = new byte[length];
//                    byteBuf.get(arr);

                    int[] intArr = new int[bytes.length];
                    for (int i = 0; i < bytes.length; i++) {
                        intArr[i] = Byte.toUnsignedInt(bytes[i]);
                    }
                    int[] bayerArr = BayerUtil.bayer2RGB_GB_3(intArr, width, height);
                    byte[] bytes1 = new byte[bayerArr.length];
                    for (int i = 0; i < bayerArr.length; i++) {
                        bytes1[i] = (byte) bayerArr[i];
                    }
//                        int[] newArray = new int[bytes.length];
//                        for (int i = 0; i < bytes.length; i++) {
//                            newArray[i] = bytes[i];
//                        }
//                        int[] bayerArr = BayerUtil.bayer2RGB_GB_3(newArray, width, height);
//                        byte[] arr = new byte[bayerArr.length];
//                        for (int i = 0; i < bayerArr.length; i++) {
//                            arr[i] = (byte) bayerArr[i];
//                        }
                        String idStr = IdWorker.getIdStr();
                        int png = LaptopConstant.nativeImageIO.write2BGRAndScale(bytes1, height, width, "/data/images/", idStr + ".png", "png",0.1d);

                        //base64生成图片的方式   String base64 = Base64.getEncoder().encodeToString(FileUtil.readBytes("/data/" + idStr + ".png"));
                        String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".png";
                        //log.info("合成成功："+imageUrl);
                        content.put("imageUrl", imageUrl);
                        content.put("idsName", idsName);

                        String[] split = secondStr.split(":");
                        content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                        content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
                    content.put("key", key);
                    log.info("流体柜 6D22H_2FH,6D27H_2FH, 合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");
                    return content;
                },taskExecutePool.threadPoolTaskExecutor2());
                LaptopConstant.imageFutureList.add(future);

            }

            queue = new StringBuilder();
            queue.append(dataFrames);
            LaptopConstant.imageData.put(key, queue);

        }
        LaptopConstant.imageNumMap.put(key, currImageNum);
        return true;
    }

    public static int[] toIntArr(String str) {
        int length = str.length();
        int[] result = new int[length];
        // 依次取得字符串中的每一个字符，并将其转化为数字，放进int数组中
        for (int i = 0; i < length; i++) {
            char c = str.charAt(i);
            result[i] = Character.getNumericValue(c);
        }
        return result;
    }


    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");
        //D:\\pc_workspace\\数据\\流体柜\    //显微CMOS图像数据  //高速CCD图像数据
        List<String> strings = FileUtil.readUtf8Lines("D:\\pc_workspace\\流体物理实验柜1301\\高速CCD图像数据.txt");
        LiutiguiApp3or19Service liutiguiApp3or19Service = new LiutiguiApp3or19Service();

        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);

            liutiguiApp3or19Service.merge(jsonObject, "TGMTYY1301_06BH_31_FPRAPP3", "TGMTYY1301_06BH_31_FPRAPP3");
        }

    }


}
